package com.robot.web.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.robot.web.common.util.BizLogger;
import com.robot.web.constant.MessageConstant;


public class SecurityInterceptor implements HandlerInterceptor {
	
	public BizLogger logger = BizLogger.getLogger(this.getClass());
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// if(handler instanceof HandlerMethod){

		String[] noFilters = new String[] {
				MessageConstant.COMMON_NOFILTER_URL_STATIC,
				MessageConstant.COMMON_NOFILTER_URL_LOGIN,
				MessageConstant.COMMON_NOFILTER_URL_LOGINSUBMIT,
				MessageConstant.COMMON_NOFILTER_URL_LOGOUT,
				MessageConstant.COMMON_NOFILTER_URL_ERROR};
		String uri = request.getRequestURI();
		/*
		logger.debug("preHandle request uri=" + uri);

		boolean beFilter = true;
		for (String s : noFilters) {
			if (uri.indexOf(s) != -1) {
				beFilter = false;
				break;
			}
		}
		if (beFilter) {
			Object obj = request.getSession().getAttribute(
					MessageConstant.COMMON_AUTHORISED);
			if (obj == null || "".equals(obj.toString())) {
				logger.debug("------------------------Not Authorised");

				boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
				PrintWriter out = response.getWriter();
				String appContext = request.getContextPath();

				String basePath = request.getScheme() + "://"+ request.getServerName() + ":"+ request.getServerPort() + appContext;
                // for anync requst by ajax
				if (isAjax&& request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
					
					out.write("timeout");
				} else {
					StringBuilder builder = new StringBuilder();
					builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
					builder.append("alert(\"Please login\");");
					builder.append("window.top.location.href=\"");
					builder.append(basePath);
					builder.append("/" + MessageConstant.LOGIN_URL+ "\";</script>");
					out.print(builder.toString());

				}
				out.flush();
				out.close();
				return false;

			}
		}
		*/
		return true;
	}
}